package Threelayer.Utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lishunlin110
 * @version 1.0
 * @description: Dao工具类
 * @date 2021/8/23 13:07
 */
public class DaoUtils<T> {

    /**
     * 公共处理增删改查方法
     * @param sql 要执行的sql语句
     * @param args 可变长参数列表
     * @return 更新结果
     */
    public int commonsUpdate(String sql,Object... args){
        Connection connection = DbUtils.getConnection();
        PreparedStatement ps=null;

        try {
            ps=connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i+1,args[i]);
            }
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DbUtils.closeAll(null,ps,null);
        }
        return 0;
    }

    public List<T> commonsQuery(String sql,RowMapper<T> rowMapper, Object... args){
        Connection con ;
        PreparedStatement ps ;
        ResultSet rs ;
        List<T> list = new ArrayList<>();
        con = DbUtils.getConnection();
        try {
            ps = con.prepareStatement(sql);
            if(args!=null){
                for (int i = 0; i < args.length; i++) {
                    ps.setObject(i+1,args[i]);
                }
            }
            rs = ps.executeQuery();
            while (rs.next()){
                T t= rowMapper.getRow(rs);
                list.add(t);
            }
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
